package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ResetPasswordDTO;
import com.sky.dto.UserInfoUpdateDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.UserRegisterDTO;
import com.sky.entity.User;
import com.sky.exception.EmailErrorException;
import com.sky.exception.PasswordErrorException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.EmailUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 贾晓晨
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理接口")
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 生成登录成功的响应
     * @param user 用户信息
     * @return 登录成功的响应
     */
    private Result<UserLoginVO> generateLoginResponse(User user) {
        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getId());
        claims.put(JwtClaimsConstant.Permission, user.getPermission());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        // 构建登录成功返回的VO
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        return generateLoginResponse(user);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    @Transactional(rollbackFor = Exception.class)
    public Result<UserLoginVO> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册：{}", userRegisterDTO);

        // 检查用户名和邮箱是否已存在
        if (userService.isUsernameExists(userRegisterDTO.getUsername())!=null) {
            return Result.error(MessageConstant.USERNAME_SOLE);
        }
        if (userService.isEmailExists(userRegisterDTO.getEmail())!=null) {
            return Result.error(MessageConstant.EMAIL_SOLE);
        }

        // 注册用户
        userService.register(userRegisterDTO);
        // 注册成功后，使用注册信息进行登录
        UserLoginDTO loginDTO = new UserLoginDTO();
        loginDTO.setUsername(userRegisterDTO.getUsername());
        loginDTO.setPassword(userRegisterDTO.getPassword());
        User user = userService.login(loginDTO);
        return generateLoginResponse(user);
    }

    @GetMapping("/forget")
    @ApiOperation("发送验证码")
    public Result<String> forget(@RequestParam String email) {
        log.info("开始向{}发送邮件",email);
        String code = "";
        // 是否存在
        String isCode =(String) redisTemplate.opsForValue().get("emailCode:" + email);
        if (isCode==null) {
            Random random = new Random();
            code = String.format("%04d", random.nextInt(1000000));
            // 保存code
            redisTemplate.opsForValue().set("emailCode:" + email, code, 5, TimeUnit.MINUTES); //
        }else{
            code = isCode;
        }
        boolean success = emailUtil.sendEmail(email, code);
        log.info("发送结果{}",success);
        if(!success){
            throw new EmailErrorException(MessageConstant.EMAIL_SEND_FAILED);
        }
        return Result.success(MessageConstant.EMAIL_SEND_SUCCESS);
    }

    @PatchMapping("/resetPassword")
    @ApiOperation("重置密码")
    public Result<String> resetPassword(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        String email = resetPasswordDTO.getEmail();
        String code =(String) redisTemplate.opsForValue().get("emailCode:" + email);
        if(code==null){
            // throw new EmailErrorException("验证码已过期");
            return Result.error("验证码已过期");
        }else if(!code.equals(resetPasswordDTO.getCode())){
            // throw new EmailErrorException("验证码不正确");
            return Result.error("验证码不正确");
        }
        if (code != null && code.equals(resetPasswordDTO.getCode())) {
            userService.resetPassword(resetPasswordDTO);
        }
        return Result.success("重置密码成功");
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public Result<String> logout(HttpServletRequest request) {
        // 从请求头获取令牌
        String token = request.getHeader("Authorization");
        if (StringUtils.hasText(token) && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            // 解析令牌获取声明信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);

            // 计算令牌剩余有效时间
            Date expiration = claims.getExpiration();
            long ttlMillis = expiration.getTime() - System.currentTimeMillis();

            if (ttlMillis > 0) {
                // 将令牌加入黑名单（使用Redis存储）
                redisTemplate.opsForValue().set(
                        "jwt:blacklist:" + token,
                        "logged-out",
                        ttlMillis,
                        TimeUnit.MILLISECONDS
                );
            }
            BaseContext.removeCurrent();
            return Result.success("退出成功");
        } catch (Exception e) {
            // 处理无效或过期的令牌
            throw new RuntimeException("令牌无效或已过期");
        }
    }

    @PutMapping("/updateInfo")
    @ApiOperation("更新昵称和头像")
    public Result updateInfo(@RequestBody UserInfoUpdateDTO userInfoUpdateDTO){
        userService.updateInfo(userInfoUpdateDTO);
        return Result.success("更新成功");
    }

    @GetMapping("getAvatar")
    @ApiOperation("获取头像")
    public Result<String> getAvatar(){
        String avatar = userService.getAvatar();
        return  Result.success(avatar);
    }
}